//
//  LogisticsFormVC.swift
//  SlaughterClient
//
//  Created by 邱仙凯 on 2021/6/10.
//  Copyright © 2021 zwb. All rights reserved.
//

import UIKit

class ZyaLogisticsFormVC: UIViewController, UITableViewDelegate, UITableViewDataSource, operatable, refreshable, DateWidgetable {
    var idkey:String = ""
    var main = ZyaLogisticsModel(JSON:["":""])!
    var details = [ZyaLogisticsDetail]()
    
    var imageArray = [VideoImg]()
    
    static func initForFix(idkey:String) -> ZyaLogisticsFormVC {
        let vc = ZyaLogisticsFormVC()
        vc.excuteType = .fix
        vc.idkey = idkey
        return vc
    }
    
    static func initForView(idkey: String) -> ZyaLogisticsFormVC {
        let vc = ZyaLogisticsFormVC()
        vc.excuteType = .view
        vc.idkey = idkey
        return vc
    }
    
    static func initForAudit(model: ZyaLogisticsModel) -> ZyaLogisticsFormVC {
        let vc = ZyaLogisticsFormVC()
        vc.excuteType = .audit
        vc.main = model
        return vc
    }

    static func initForAdd() -> ZyaLogisticsFormVC {
        let vc = ZyaLogisticsFormVC()
        vc.excuteType = .add
        return vc
    }
    
    // 防止外面乱初始化，并提供静态方法给调用者
    private init() {
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var tableView: UITableView = {
        return UITableView(frame: self.view.bounds).then {
            $0.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 100, right: 0)
            $0.delegate = self
            $0.dataSource = self
            $0.rowHeight = 274
            $0.separatorStyle = .none
            $0.backgroundColor = UIColor(kshex: "#f2f2f2")
            $0.register(cellWithClass: ZyaLogisticsFormCell.self)
        }
    }()
    
    lazy var header = ZyaLogisticsHeader(frame: CGRect(x: 0, y: 0, width: KSGlobal.screenW, height: 0))
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "动保发货"
        self.view.addSubview(self.tableView)
        
        if excuteType == .add {
            self.main.zStaffId = USERINFO.usrid.unwrap
            self.main.zStaffNm = USERINFO.username.unwrap
            self.main.zStatus = "0"
            self.main.zDeliveryType = "0"
            
            let dAddrArr = zyasendAddrArr.filter { $0.currMark == 1 }
            if dAddrArr.count > 0 {
                self.main.zConsignerNm = dAddrArr.first!.kLinkName
                self.main.zConsignerTel = dAddrArr.first!.kLinkPhone
                self.main.zProvinceFh = dAddrArr.first!.kProvince
                self.main.zCityFh = dAddrArr.first!.kCity
                self.main.zDistrictFh = dAddrArr.first!.kArea
                self.main.zConsignerAddress = dAddrArr.first!.clientAdd
                
            }
        }
        
        header.excuteType = self.excuteType
        self.header.one = self.main
        self.tableView.tableHeaderView = header
        
        header.addImgBlock = { [unowned self] one in
            self.imageArray.append(contentsOf: one)
        }
        
        header.deleteImgBlock = { [unowned self] needNet, one, index in
            if needNet {
                alertUtil(self, title: "确认删除", operateS: [nameAction(name: "确认", action: { _ in
                    KSNetwork.shared.doRequest(API.deleteFile(id_key: one.idkey.unwrap)) { (data:BaseResult<OperateResult>) in
                        if data.flag == TRUE {
                            self.imageArray.remove(at: index)
                            self.header.imageArray.remove(at: index)
                        } else {
                            KSToast(data.errorCombine.unwrap)
                        }
                    }
                })])
            } else {
                
                self.imageArray.remove(at: index)
            }
        }
       
        header.segmentClosure = { index in
            self.main.zDeliveryType = "\(index)"
            self.header.one = self.main
            self.header.imageArray = self.imageArray
           
            self.tableView.tableHeaderView = self.header
        }
        
        header.hetongClosure = {
            if self.excuteType == .add {
                self.getHetong()
            }
        }
        
        header.shouhuorenClosure = {
            self.getShouhuoren()
        }
        header.fahuorenClosure = {
            self.getFahuoren()
        }
        header.textSelectClosure = { tag in
            switch tag {
            case 1:
                if self.excuteType == .add {
                    self.getHetong()
                }
            case 3:
                self.showDateSelect(self) { str in
                    self.main.zConsignerDate = str
                    self.header.one = self.main
                    self.header.imageArray = self.imageArray
                    self.tableView.tableHeaderView = self.header
                }
            case 6:
                let vc = ProvinceCityController(selectType: .proCityDict)
                vc.tripleSelectClosure = { province,city,district in
                    
                    self.main.zProvinceFh = province
                    self.main.zCityFh = city
                    self.main.zDistrictFh = district
                    self.header.one = self.main
                    self.header.imageArray = self.imageArray
                    self.tableView.tableHeaderView = self.header
                }
                self.navigationController?.pushViewController(vc, animated: true)
            case 10:
                let vc = ProvinceCityController(selectType: .proCityDict)
                vc.tripleSelectClosure = { province,city,district in
                    
                    self.main.zProvinceSh = province
                    self.main.zCitySh = city
                    self.main.zDistrictSh = district
                    self.header.one = self.main
                    self.header.imageArray = self.imageArray
                    self.tableView.tableHeaderView = self.header
                }
                self.navigationController?.pushViewController(vc, animated: true)
            case 12:
                KSNetwork.shared.doRequest(API.queryLogisticsCompany) { (data:BaseResult<OperateResult>) in
                    if data.flag == TRUE {
                        if let infos = data.infos {
                            var allArr = [nameAndModel<OperateResult>]()
                            for item in infos {
                                let one_x = nameAndModel(shows: [item.z_wl_org_nm.unwrap], model: item)
                                allArr.append(one_x)
                            }
                            let cle:(nameAndModel<OperateResult>)->() = { one in
                                self.main.zLogisticsNm = one.model.z_wl_org_nm
                                self.header.one = self.main
                                self.header.imageArray = self.imageArray
                                self.tableView.tableHeaderView = self.header
                            }
                            let vc = KSSingleSelectUtil.initWithNav(title: "物流公司列表", allArr: allArr, backClosure: cle)
                            self.present_FullScreen(to: vc)
                        }
                    } else {
                        KSToast(data.message.unwrap)
                    }
                    
                    
                }
                
                
            default:
                break
            }
        }
        header.textEndEditClosure = { tag,str in
            switch tag {
           
            case 7:
                self.main.zConsignerAddress = str
                self.header.one = self.main
                self.header.imageArray = self.imageArray
                self.tableView.tableHeaderView = self.header
            case 11:
                self.main.zConsigneeAddress = str
                self.header.one = self.main
                self.header.imageArray = self.imageArray
                self.tableView.tableHeaderView = self.header
            default:
                break
            }
        }
        header.textClosure = {tag,str in
            switch tag {
            case 4:
                self.main.zConsignerNm = str
            case 5:
                self.main.zConsignerTel = str
           
            case 8:
                self.main.zConsigneeNm = str
            case 9:
                self.main.zConsigneeTel = str
       
            case 13:
                self.main.zLogisticsNo = str
            default:
                break
            }
        }
        
        if excuteType == .fix || excuteType == .view  {
            KSNetwork.shared.doRequest(API.getLogistics(id_key: self.idkey)) { (data:BaseResult<ZyaLogisticsModel>) in
                if data.flag == TRUE {
                    if let info = data.info_object {
                        self.main = info
                
                        
                        if let det = info.detail {
                            let newArr = det.compactMap { model -> ZyaLogisticsDetail in
                                var xModel = model
                                xModel.ztbFileUrl = self.main.ztbFileUrl
                                return xModel
                            }
                            self.details =  newArr
                        }
                    }
                    self.header.one = self.main
                    self.tableView.reloadData()
                    
                    self.getFiles()
                    
                } else {
                    KSToast(data.message)
                }
            }
        }
        if self.excuteType == .add || self.excuteType == .fix {
            let btn = UIButton()
            btn.setTitle("保存", for: .normal)
            btn.layer.masksToBounds = true
            btn.layer.cornerRadius = 20
            btn.backgroundColor = Theme.primaryColor()
            self.view.addSubview(btn)
            btn.snp.makeConstraints { make in
                make.top.equalTo(self.view).offset( KSGlobal.screenH -  self.navigationController!.navigationBar.frame.height - heightOfAddtionalHeader - 10)
                make.centerX.equalTo(self.view)
                make.width.equalTo(KSGlobal.screenW - 40)
                make.height.equalTo(40)
            }
            btn.addTouchUpInSideAction { _ in
                
                self.saveAction()
            }
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: ZyaLogisticsFormCell.self, for: indexPath)
        cell.excuteType = self.excuteType
      
        cell.one = self.details[indexPath.section]
    
        cell.textClosure = { [indexPath] tag,str in
            switch tag {
                case 1:
                    self.details[indexPath.section].zGoodsNm = str
                case 2:
                    self.details[indexPath.section].zSpec = str
                case 3:
                    self.details[indexPath.section].zUnit = str
                case 4:
                    self.details[indexPath.section].zAmountFh = str
                case 5:
                    self.details[indexPath.section].zSendAmount = str
                case 6:
                    self.details[indexPath.section].zUniqueCode = str
                case 7:
                    self.details[indexPath.section].zVender = str
                case 8:
                    self.details[indexPath.section].zProduceDate = str
                default:
                    break
            }
        }
        cell.textSelectClosure = { [indexPath] tag in
            if tag == 6 {
                self.showDateSelect(self) { str in
                    self.details[indexPath.section].zValidDate = str
                    self.tableView.reloadData()
                }
            }
            if tag == 66 {
                self.showDateSelect(self) { str in
                    self.details[indexPath.section].zProduceDate = str
                    self.tableView.reloadData()
                }
            }
        }
        
        cell.deleteClosure = { [indexPath] in
            alertUtil(self, title: "确认删除？", operateS: [nameAction(name: "确定", action: { (_) in
                self.details.remove(at: indexPath.section)
                self.tableView.reloadData()
            })])
        }
        
        return cell
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.details.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }
    
//    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//        let contentVWidth = KSGlobal.screenW
//        let bottomV = UIView(frame: CGRect(x:0,y:0,width: contentVWidth,height: 40))
//
//        let bg = UIView(frame: CGRect(x:0,y:0,width: contentVWidth,height: 38))
//        bottomV.addSubview(bg)
//        bg.backgroundColor = #colorLiteral(red: 0.8392490219, green: 0.9684520515, blue: 1, alpha: 1)
//
//        let tap = UITapGestureRecognizer()
//        tap.numberOfTapsRequired = 1
//        tap.addTap { _ in
//            //            self.details[section].0.open = !self.details[section].0.open
//            //            let set = IndexSet(integer:section)
//            //            tableView.reloadSections(set, with:UITableView.RowAnimation.automatic)
//            //
//        }
//
//        bg.addGestureRecognizer(tap)
//
//        //        let lab = self.details[section].1
//        //        lab.frame = CGRect(x:10,y:0,width: contentVWidth - 73,height: 38)
//        //        lab.font = UIFont.systemFont(ofSize: 16)
//        //        lab.text  = "\(self.details[section].0.zBatchNm.unwrap)"
//        //        bg.addSubview(lab)
//        if self.excuteType == .add  {
//            let delete = UIButton(frame: CGRect(x:contentVWidth - 60,y:5,width: 27,height: 27))
//            delete.setImage(UIImage(named: "lajitong"), for: .normal)
//            delete.addTouchUpInSideAction { _ in
//                alertUtil(self, title: "确认删除？", operateS: [nameAction(name: "确定", action: { (_) in
//                    self.details.remove(at: section)
//                    self.tableView.reloadData()
//                })])
//
//            }
//            bg.addSubview(delete)
//        }
//        //        let img = UIImageView(image: UIImage(named: self.details[section].0.open == true ? "filter_up" : "filter_down"))
//        //        img.frame = CGRect(x:contentVWidth - 20,y:16,width: 12,height: 8)
//        //        bg.addSubview(img)
//
//        return bottomV
//    }
    //MARK: - Network
    func getFiles() {
        KSNetwork.shared.doRequest(API.getFileList(vou_id: idkey)) { [weak self] (data: BaseResult<OperateResult>) in
            if data.flag == TRUE {
                guard let self = `self` else { return }
                
                for (_, dic) in data.infoDicArr.enumerated() {
                    var img = VideoImg()
                    img.idkey = dic["id_key"].unwrap
                    img.url = dic["file_url"].unwrap
                    if let url = URL(string: img.url) {
                        do {
                            let fileData = try NSData(contentsOf: url, options: .dataReadingMapped)
                            img.data = fileData as Data
                        } catch {
                            
                        }
                    }
                    
                    let name = dic["file_name"].unwrap
                    
                    if name.hasSuffix(".jpg") {
                        img.type = .image
                    } else if name.hasSuffix(".pdf") {
                        img.type = .file
                    }
                    
                    self.imageArray.append(img)
                }
                
                if self.imageArray.count > 0 {
                    self.header.imageArray = self.imageArray
                    self.tableView.reloadData()
                }
            }
        }
    }
    
    func uploadFiles(complete: @escaping (() -> Void)) {
        let arr = imageArray.filter { $0.idkey.unwrap.count == 0 }
        if arr.count > 0 {
            KSNetwork.shared.doRequest(API.uploadFiles(vou_id: idkey, files: arr)) { (data: BaseResult<OperateResult>) in
                if data.flag == TRUE {
                    complete()
                }
            }
        } else {
            complete()
        }
    }
    
    func getFahuoren() {
        guard !self.main.zContractId.unwrap.isEmpty else {
            KSToast("先选合同")
            return
        }
        
        let vc = KSSingleSelectNetUtil(searchType:.bar,tintColor:.white)
        vc.title = "发货人列表"
        vc.kSSingleSelectNetNetwork = { page,size,keyword in
            KSNetwork.shared.doRequest(API.queryClientAddress(k_addr_type: "1")) { (data:BaseResult<ZyaClientAddress>) in
                if data.flag == TRUE {
                    if let infos = data.infoArrCombine {
                        if page == 1 {
                            vc.allArr.removeAll()
                        }
                        vc.showData(arr: infos)
                    }
                } else {
                    KSToast("错误")
                }
            }
        }
        vc.kSSingleSelectNetShowCell = { cell,model in
            var contArr:[(String,String?)]!
            
            cell.leftBottomImg.image = UIImage(named: "dingwei1")
            
            contArr = [
                ("","\((model as! ZyaClientAddress).kLinkName.unwrap) \((model as! ZyaClientAddress).kLinkPhone.unwrap)"),
                ("","     \((model as! ZyaClientAddress).clientAdd.unwrap)")

            ]
            cell.setDataSource(contentArr: contArr)
        }
        
        vc.backClosure = { model in
            self.main.zConsignerNm = (model as! ZyaClientAddress).kLinkName
            self.main.zConsignerTel = (model as! ZyaClientAddress).kLinkPhone
            self.main.zProvinceFh = (model as! ZyaClientAddress).kProvince

            self.main.zConsignerAddress = (model as! ZyaClientAddress).clientAdd

       
            self.header.one = self.main
            self.header.imageArray = self.imageArray
            self.tableView.tableHeaderView = self.header
        }
        self.navigationController?.pushViewController(vc,animated:true)
    }
    
    func getShouhuoren() {
        guard !self.main.zContractId.unwrap.isEmpty else {
            KSToast("先选合同")
            return
        }
        
        let vc = KSSingleSelectNetUtil(searchType:.bar,tintColor:.white)
        vc.title = "收货人列表"
        vc.kSSingleSelectNetNetwork = { page,size,keyword in
            KSNetwork.shared.doRequest(API.queryAddress(page: "\(page)", size: "\(size)", z_title: keyword,z_contract_id: self.main.zContractId.unwrap)) { (data:BaseResult<ZyaReciverMain>) in
                if data.flag == TRUE {
                    if let infos = data.infos {
                        if page == 1 {
                            vc.allArr.removeAll()
                        }
                        vc.showData(arr: infos)
                    }
                } else {
                    KSToast("错误")
                }
            }
        }
        vc.kSSingleSelectNetShowCell = { cell,model in
            var contArr:[(String,String?)]!
            
            cell.leftBottomImg.image = UIImage(named: "dingwei1")

             
            contArr = [
                ("","\((model as! ZyaReciverMain).zLinkmanNm.unwrap) \((model as! ZyaReciverMain).zLinkmanTel.unwrap)")
                ,("","     \((model as! ZyaReciverMain).zProvince.unwrap)\((model as! ZyaReciverMain).zCity.unwrap)\((model as! ZyaReciverMain).zDistrict.unwrap)\((model as! ZyaReciverMain).zLinkmanAddress.unwrap)")
            ]
            cell.setDataSource(contentArr: contArr)
        }
        
        vc.backClosure = { model in
            self.main.zConsigneeNm = (model as! ZyaReciverMain).zLinkmanNm
            self.main.zConsigneeTel = (model as! ZyaReciverMain).zLinkmanTel
            self.main.zProvinceSh = (model as! ZyaReciverMain).zProvince
            self.main.zCitySh = (model as! ZyaReciverMain).zCity
            self.main.zDistrictSh = (model as! ZyaReciverMain).zDistrict
            self.main.zConsigneeAddress = (model as! ZyaReciverMain).zLinkmanAddress
            
            self.header.one = self.main
            self.header.imageArray = self.imageArray
            self.tableView.tableHeaderView = self.header
        }
        self.navigationController?.pushViewController(vc,animated:true)
    }
    
    func getHetong() {
        let vc = KSSingleSelectNetUtil(tintColor:.white)
        vc.title = "合同列表"
        vc.kSSingleSelectNetNetwork = { page,size,keyword in
            KSNetwork.shared.doRequest(API.queryContract(page: "\(page)", size: "\(size)", z_title: keyword)) { (data:BaseResult<ZyaWlContractModel>) in
                if data.flag == TRUE {
                    if let infos = data.infos {
                        if page == 1 {
                            vc.allArr.removeAll()
                        }
                        vc.showData(arr: infos)
                    }
                } else {
                    KSToast("错误")
                }
            }
        }
        vc.kSSingleSelectNetShowCell = { cell,model in
            var contArr: [(String,String?)]!
            
            contArr = [
                ("","\((model as! ZyaWlContractModel).zType.unwrap)\((model as! ZyaWlContractModel).zHtNo.unwrap)")
                //                       ,("","\((model as! EvaluateFarmModel).zName.unwrap)")
                
            ]
            cell.setDataSource(contentArr: contArr)
        }
        vc.backClosure = { model in
            self.main.zType = (model as! ZyaWlContractModel).zType
            self.main.zContractNo = (model as! ZyaWlContractModel).zHtNo
            self.main.zContractId = (model as! ZyaWlContractModel).idKey
            self.main.zSupplierNm = (model as! ZyaWlContractModel).zSupplierNm
            self.main.zSupplierId = (model as! ZyaWlContractModel).zSupplierId
            self.main.zOrgNm = (model as! ZyaWlContractModel).zOrgNm
            self.main.zOrgId = (model as! ZyaWlContractModel).zOrgId
            self.main.zAccPeriod = (model as! ZyaWlContractModel).zAccountPeriod
            self.header.one = self.main
            self.header.imageArray = self.imageArray
            self.tableView.tableHeaderView = self.header
            KSNetwork.shared.doRequest(API.queryContractGoodsNew(z_contract_id: (model as! ZyaWlContractModel).idKey.unwrap)) { (data:BaseResult<ZyaXXXModel>) in
                if data.flag == TRUE {
                    if let xxx = data.info_object {
                        if let details = xxx.details {
                            let newinfos = details.compactMap { model -> ZyaLogisticsDetail in
                                var new = model
                                new.fromContract = true
                                return new
                            }
                            self.details = newinfos
                        }
                        if let main = xxx.main {
                            self.main.zConsigneeNm = main.zLinkmanNm
                            self.main.zConsigneeTel = main.zLinkmanTel
                            self.main.zProvinceSh = main.zProvince
                            self.main.zCitySh = main.zCity
                            self.main.zDistrictSh = main.zDistrict
                            self.main.zConsigneeAddress = main.zLinkmanAddress
                        }
                    }
                }
                self.header.one = self.main
                self.header.imageArray = self.imageArray
                self.tableView.tableHeaderView = self.header
                self.tableView.reloadData()
            }
        }
        self.navigationController?.pushViewController(vc,animated:true)
    }
    
    // MARK: - 提交
    @objc func saveAction() {
        let vali = Validation()
        vali.expression(self.details.count > 0, msg: "至少需要一条细表")
        vali.required(value: self.main.zContractNo, msg: "合同不为空")
        vali.required(value: self.main.zConsignerDate, msg: "发货日期不为空")
        vali.required(value: self.main.zConsignerNm, msg: "发货人不为空")
        vali.required(value: self.main.zConsignerTel, msg: "发货人电话不为空")
        vali.required(value: self.main.zProvinceFh, msg: "发货人地区不为空")
        vali.required(value: self.main.zConsignerAddress, msg: "发货人详细地址不为空")
        vali.required(value: self.main.zConsigneeNm, msg: "收货人不为空")
        vali.required(value: self.main.zConsigneeTel, msg: "收货人电话不为空")
        vali.required(value: self.main.zProvinceSh, msg: "收货人地区不为空")
        vali.required(value: self.main.zConsigneeAddress, msg: "收货人详细地址不为空")
        if self.main.zDeliveryType == "0" {
            vali.required(value: self.main.zLogisticsNm, msg: "物流公司不为空")
            vali.required(value: self.main.zLogisticsNo, msg: "物流单号不为空")
        } else {
            
        }
        
        for i in 0..<self.details.count {
            vali.required(value: self.details[i].zGoodsNm, msg: "第\(i + 1)条细表，品名不能为空!")
            vali.required(value: self.details[i].zSpec, msg: "第\(i + 1)条细表，规格不能为空!")
            vali.required(value: self.details[i].zAmountFh, msg: "第\(i + 1)条细表，数量(不含赠品)不能为空!")
            vali.required(value: self.details[i].zValidDate, msg: "第\(i + 1)条细表，有效期不能为空!")
            //                     vali.required(value: self.details[i].zUniqueCode, msg: "第\(i + 1)条细表，唯一码不能为空!")
            
        }
        
        guard vali.validate() else {
            return
        }
        self.main.detail = details
        let masterjson = dictionaryToJson(self.main.dictionaryRepresentation())
     
        var api: API?
        if excuteType == .fix {
//            let mas = dictionaryToJson(self.details.first!.dictionaryRepresentation())
            api = API.updateLogistics(data: masterjson, detail: "")
        } else {
            api = API.saveLogistics(data: masterjson, detail: "")
        }
        
        KSNetwork.shared.doRequest(api!) {[weak self] (data:BaseResult<OperateResult>) in
            guard let `self` = self else { return }
            if data.flag == TRUE {
                if let idkey = data.infoDic?["id_key"].unwrap {
                    self.idkey = idkey
                }
                self.uploadFiles {
                    KSToast("保存单据成功")
                    self.backAction()
                }
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
        
    }
    
    func backAction() {
        if let clo = self.refreshClosure {
            clo()
        }
        self.navigationController?.popViewController(animated: true)
    }

}
